package com.chenqi.community.controller;

import com.chenqi.community.entity.*;
import com.chenqi.community.exception.OverSizeException;
import com.chenqi.community.service.CommentService;
import com.chenqi.community.service.PostService;
import com.chenqi.community.service.TagService;
import com.chenqi.community.service.TypeService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Ardai
 */
@Controller
//@RequestMapping("/community")
public class PostController {

    @Autowired
    private PostService postService;

    @Autowired
    private TagService tagService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private TypeService typeService;

    /**
     * 首页
     * @param page
     * @param rows
     * @param modelAndView
     * @return
     */

    @GetMapping("/list")
    public ModelAndView list(Integer page,Integer rows,ModelAndView modelAndView) {
        //如果不传分页信息进行预处理
//        int j=1/0;
        page = page == null ? 1 : page;
        rows = rows == null ? 8 : rows;
        //分页信息处理
        List<Post> postList = postService.findByPage(page, rows);
        Integer total = postService.findPostCount();
        Integer totalPages = total % rows == 0 ? total / rows : total / rows + 1;
        List<Integer> pageList = new ArrayList<>();
        for (int i=1;i<=totalPages;i++){
            pageList.add(i);
        }
        //封装分页信息
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPage(page);
        pageInfo.setRows(rows);
        pageInfo.setPostList(postList);
        pageInfo.setPageList(pageList);
        pageInfo.setTotalPages(totalPages);
        modelAndView.addObject("pageInfo", pageInfo);
        modelAndView.setViewName("index");
        //标签
        List<Tag> tags = tagService.findAllTags();
        modelAndView.addObject("tags", tags);
        //类型
        List<Type> types = typeService.findAllType();
        modelAndView.addObject("types", types);
        //进行什么类型的分页的进行返回
        modelAndView.addObject("status", 0);
        return modelAndView;
    }

    /**
     * 查看帖子详情
     * @param pid
     * @param modelAndView
     * @return
     */

    @GetMapping("/post")
    public ModelAndView post(Integer pid,Integer noView,ModelAndView modelAndView){
        //预处理noView参数
        noView = noView == null ? 0 : noView;
        //对应的帖子
        Post post = postService.findPostById(pid);
        //点击查看数然后更新查看记录(如果是评论之后重定向就不需要更新)
        if (noView==0){
            post.setView(post.getView()+1);
            postService.editPostInfo(post);
        }
        modelAndView.addObject("post", post);
        //标签
        List<Tag> tags = tagService.findTagsByPostId(pid);
        modelAndView.addObject("tags", tags);
        //推送其他(默认推送最新8条)
        List<Integer> allPostId = postService.findAllPostId();
        List<Post> pushPost = new ArrayList<>();
        for (Integer id : allPostId) {
            if (pushPost.size()<=7){
                Post post1 = postService.findPostById(id);
                pushPost.add(post1);
            }else {
                break;
            }
        }
        modelAndView.addObject("pushPost", pushPost);
        //评论
        List<Comment> comments = commentService.findCommentsByPostId(pid);
        modelAndView.addObject("comments", comments);
        modelAndView.setViewName("postDetail");
        return modelAndView;
    }

    /**
     * 新增帖子
     * @param postRequest
     * @param tags
     * @param session
     * @param modelAndView
     * @return
     */

    @PostMapping("/addPost")
    public ModelAndView addPost(PostRequest postRequest, MultipartFile postImg, String[]  tags , HttpSession session, ModelAndView modelAndView) throws IOException {
        User user = (User) session.getAttribute("user");
        Post post = new Post();
        post.setUserId(user.getId());
        post.setUserAvatar(postRequest.getUserAvatar());
        post.setUserAvatar(user.getAvatar());
        post.setTitle(postRequest.getTitle());
        post.setContent(postRequest.getContent());
        post.setTypeId(postRequest.getTypeId());
        //帖子附图(如果用户不选附图就不上传)
        if (postImg!=null){
            String realPath = ResourceUtils.getURL("classpath:").getPath() + "static/postImg";
            //如果目录不存在就创建
            File dir = new File(realPath);
            if (!dir.exists()) dir.mkdirs();
            //修改上传附图的文件名
            String extension = FilenameUtils.getExtension(postImg.getOriginalFilename());
            String prefix = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            String newFileName = prefix + "." + extension;
            //暂时写入服务器
            postImg.transferTo(new File(realPath,newFileName));
            //将相对于服务器的路径存入数据库
            String dataPath = realPath.substring(realPath.lastIndexOf("/"));
            String dataImgPath = dataPath + "/" + newFileName;
            post.setPostImg(dataImgPath);
        }
        modelAndView.setViewName("redirect:/list");
        postService.addPost(post,tags);
        return modelAndView;
    }

    /**
     * 根据帖子标题查询
     * @param page
     * @param rows
     * @param title
     * @param modelAndView
     * @return
     */

    @GetMapping("/search")
    public ModelAndView search(Integer page,Integer rows,String title,ModelAndView modelAndView) {
        //如果什么都不输入点击搜索就查询所有
        if (title==null || title==""){
            modelAndView.setViewName("redirect:/list");
            return modelAndView;
        }
        //如果不传分页信息进行预处理
        page = page == null ? 1 : page;
        rows = rows == null ? 4 : rows;
        //获取分页信息
        PageInfo pageInfo = new PageInfo();
        Integer total = postService.findSearchTitleCount(title);
        Integer totalPages = total % rows == 0 ? total / rows : total / rows + 1;
        List<Post> postByTitle = postService.findPostByTitle(page, rows, title);
        List<Integer> pageList = new ArrayList<>();
        for (int i=1;i<=totalPages;i++){
            pageList.add(i);
        }
        //封装分页信息
        pageInfo.setPage(page);
        pageInfo.setRows(rows);
        pageInfo.setTotalPages(totalPages);
        pageInfo.setPostList(postByTitle);
        pageInfo.setPageList(pageList);
        pageInfo.setOther(title);
        //标签
        List<Tag> tags = tagService.findAllTags();
        modelAndView.addObject("tags", tags);
        modelAndView.addObject("pageInfo", pageInfo);
        //分类
        List<Type> types = typeService.findAllType();
        modelAndView.addObject("types", types);
        //进行什么类型的分页的进行返回
        modelAndView.addObject("status", 2);
        modelAndView.setViewName("index");
        return modelAndView;
    }

}
